﻿using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Interactivity;
using iOSClub.App.Desktop.ProjectPages;
using iOSClub.App.Desktop.ViewModels.Pages;
using iOSClub.App.Desktop.ViewModels.ProjectPages;
using iOSClub.App.Desktop.Views;
using iOSClub.App.Share;
using iOSClub.App.Share.Serves;

namespace iOSClub.App.Desktop.Pages;

public partial class ProjectPage : UserControl
{
    public ProjectPage()
    {
        InitializeComponent();
    }

    protected override async void OnInitialized()
    {
        base.OnInitialized();
        if (DataContext is not ProjectPageModel model) return;
        var main = ViewOpera.GetView<MainView>(this);
        if (main == null) return;
        using var proj = new ProjectServer(main.Jwt);
        if (main.User.IsAdmin())
        {
            AllRing.IsVisible = true;
            var all = await proj.GetAllData();
            foreach (var projectModel in all)
            {
                model.AllProjects.Add(projectModel);
            }

            AllBlock.IsVisible = true;
            AllRing.IsVisible = false;
            AllEmpty.IsVisible = all.Count == 0;
        }

        var data = await proj.GetYourProjects();
        foreach (var item in data)
        {
            model.YourProjects.Add(item);
        }

        YourRing.IsVisible = false;
        EmptyControl.IsVisible = data.Count == 0;

        var task = await proj.GetYourTasks();
        foreach (var item in task)
        {
            model.YourTasks.Add(item);
        }

        TaskEmpty.IsVisible = task.Count == 0;
        TaskRing.IsVisible = false;
    }

    private void ProjectClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control button) return;
        if (button.DataContext is not ProjectModel model) return;
        var view = ViewOpera.GetView<MainView>(this);
        if (DataContext is not ProjectPageModel pageModel) return;
        var data = new ProjectViewModel
        {
            Project = model
        };
        foreach (var project in pageModel.YourProjects)
        {
            data.Projects.Add(project);
        }

        view?.Navigate(new ProjectView() { DataContext = data });
    }

    private void AddProjectClick(object? sender, RoutedEventArgs e)
    {
        var view = ViewOpera.GetView<MainWindow>(this);
        view?.NotificationShow("iOS Club App", "暂不支持添加项目", NotificationType.Warning);
    }
}